import {
    _decorator,
    Component,
    Camera,
    Vec3,
    input,
    Input,
    KeyCode,
    EventMouse,
    clamp,
    Size,
} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CameraController2D')
export class CameraController2D extends Component {
    // 拖拽引用的 Camera 组件
    @property({ type: Camera })
    public camera: Camera | null = null;

    // 缩放相关
    @property
    public zoomSpeed = 10; // 每单位滚轮缩放量
    @property
    public minOrthoHeight = 100; // 最小正交高度（最小视野）
    @property
    public maxOrthoHeight = 1000; // 最大正交高度（最大视野）

    // 移动相关
    @property
    public moveSpeed = 200; // 摄像机移动速度（单位：像素/秒）

    private _moveDir = new Vec3(0, 0, 0);

    onLoad() {
        // 未引用摄像机则禁用该组件
        if (!this.camera) {
            this.enabled = false;
            return;
        }

        // 监听鼠标滚轮
        input.on(Input.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
    }

    onEnable() {
        // 监听按键状态
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

    onDisable() {
        input.off(Input.EventType.MOUSE_WHEEL, this.onMouseWheel, this);
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

    // 鼠标滚轮回调，用来缩放正交摄像机的 orthoHeight
    private onMouseWheel(event: EventMouse) {
        // Cocos Camera 2D 默认使用正交投影，通过 orthoHeight 控制视野高度
        let cam = this.camera!;
        let delta = event.getScrollY();
        let newHeight = cam.orthoHeight - delta * this.zoomSpeed;
        cam.orthoHeight = clamp(
            newHeight,
            this.minOrthoHeight,
            this.maxOrthoHeight,
        );
    }

    // 按键按下：更新移动方向
    private onKeyDown(event) {
        switch (event.keyCode) {
            case KeyCode.KEY_W:
                this._moveDir.y = 1;
                break;
            case KeyCode.KEY_S:
                this._moveDir.y = -1;
                break;
            case KeyCode.KEY_A:
                this._moveDir.x = -1;
                break;
            case KeyCode.KEY_D:
                this._moveDir.x = 1;
                break;
        }
    }

    // 按键松开：更新移动方向
    private onKeyUp(event) {
        switch (event.keyCode) {
            case KeyCode.KEY_W:
            case KeyCode.KEY_S:
                this._moveDir.y = 0;
                break;
            case KeyCode.KEY_A:
            case KeyCode.KEY_D:
                this._moveDir.x = 0;
                break;
        }
    }

    update(deltaTime: number) {
        // 平滑移动摄像机
        if (this._moveDir.x !== 0 || this._moveDir.y !== 0) {
            let dir = this._moveDir.normalize();
            let movement = dir.multiplyScalar(this.moveSpeed * deltaTime);
            let pos = this.camera!.node.position.clone();
            pos.x += movement.x;
            pos.y += movement.y;
            this.camera!.node.setPosition(pos);
        }
    }
}
